/* Quiz Manager - Create and edit web quizzes.
 * Copyright (C) 2008  Alexis Brunet, Jean-Michel Brunet, Enrique Hotes, Carlo Russo
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package soen343.application;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import soen343.domain.NumericQuestion;
import soen343.domain.NumericQuestionMapper;
import soen343.domain.Question;
import soen343.domain.Quiz;
import soen343.domain.QuizMapper;

public class UpdateNumericCommand extends FrontCommand {

	@Override
	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
				
		String name = request.getParameter("name");
		int questionId = Integer.parseInt( request.getParameter("QuestionId") );
		int quizId = Integer.parseInt( request.getParameter("QuizId") );
		 
		NumericQuestion nq = new NumericQuestion(quizId, name, questionId);
		nq.setText((String)request.getParameter("text"));
		nq.setBounds(
			Double.parseDouble( request.getParameter("upperBound") ), 
			Double.parseDouble( request.getParameter("lowerBound") ));

		ArrayList<String> errors = new ArrayList<String>();
		
		if(questionId == Question.NOT_IN_DATABASE) {
			try {
				NumericQuestionMapper.insert(nq);
			} catch (Exception e) {
				errors.add("A question with that name already exists");
				request.setAttribute("errors", errors);
				request.setAttribute("question", nq);
				forward("/EditQuestion.jsp", request, response);
				return;
			}
		} else {
			NumericQuestionMapper.update(nq);
		}
		
		Quiz quiz = QuizMapper.findById(quizId);
		
		try {
			QuizMapper.closeConnection();
		} catch(SQLException e) {}
		
		if(quiz == null) {
			request.setAttribute("exception", new Exception("Could not find Quiz with id: " + quizId));
			forward("/Error.jsp", request, response);
			return;
		}
		
		request.setAttribute("quiz", quiz);
		forward("/EditQuiz.jsp", request, response);
	}

}
